import csv
import statistics
import matplotlib.pyplot as plt
from docx import Document
from docx.shared import Inches


#脚本使用需要python3版本
#yum install -y python3
#脚本使用需要安装matplotlib库
#脚本使用需要安装python-docx库
#yum install -y  libtiff-devel libjpeg-devel openjpeg2-devel zlib-devel     freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel     harfbuzz-devel fribidi-devel libraqm-devel libimagequant-devel libxcb-devel
#pip3 install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
#pip3 install python-docx -i https://pypi.tuna.tsinghua.edu.cn/simple



# 读取CSV文件
data = []
with open('Data.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        data.append(row)

# 计算新指标
for row in data:
    row['memory speed(MiB/s)'] = (float(row['8KiB memory speed(MiB/s)']) + float(row['4KiB memory speed(MiB/s)'])) / 2
    row['IO speed(次/秒)'] = (float(row['File operations read(次/秒)']) + float(row['File operations write(次/秒)'])) / 2
    row['Throughput speed(MiB/s)'] = (float(row['Throughput read(MiB/s)']) + float(row['Throughput write(MiB/s)'])) / 2

# 获取所有不同的指标
indicators = ['CPU speed(events/s)', 'memory speed(MiB/s)', 'IO speed(次/秒)', 'Throughput speed(MiB/s)']

# 创建每个IP的性能字典
ip_performance = {}
for row in data:
    ip = row['TestIP']
    if ip not in ip_performance:
        ip_performance[ip] = {indicator: [] for indicator in indicators}
    for indicator in indicators:
        ip_performance[ip][indicator].append(float(row[indicator]))



# 创建文档
doc = Document()
doc.add_heading('综合性能测试报告', level=1)

# 添加性能指标解释
doc.add_heading('性能指标解释', level=2)
doc.add_paragraph('本报告中使用了以下四个性能指标进行性能评估：')
doc.add_paragraph('1. CPU speed(events/s)：CPU 的处理速度，即每秒钟可以处理的事件数。')
doc.add_paragraph('2. Memory speed(MiB/s)：内存的数据传输速度，结合了8KiB memory speed 和 4KiB memory speed 的平均值。')
doc.add_paragraph('3. IO speed(次/秒)：文件操作的速度，包括读取和写入操作的平均值。')
doc.add_paragraph('4. Throughput speed(MiB/s)：数据传输速率，包括读取和写入速度的平均值。')
doc.add_paragraph('通过这些指标，我们可以综合评估服务器的CPU、内存、IO和数据传输性能。')

# 添加每个IP的测试数据计算结果表格
for ip, performance_data in ip_performance.items():
    doc.add_heading(f'服务器 {ip}', level=2)

    table = doc.add_table(rows=1, cols=4)
    table.style = 'Table Grid'
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '指标'
    hdr_cells[1].text = '平均值'
    hdr_cells[2].text = '标准差'
    hdr_cells[3].text = '单位'

    for indicator, values in performance_data.items():
        row_cells = table.add_row().cells
        row_cells[0].text = indicator
        row_cells[1].text = f'{statistics.mean(values):.2f}'
        row_cells[2].text = f'{statistics.stdev(values):.2f}'
        if 'speed' in indicator:
            unit = indicator.split('(')[-1].split(')')[0]
            row_cells[3].text = unit
        elif 'Throughput' in indicator:
            row_cells[3].text = 'MiB/s'
        else:
            row_cells[3].text = '次/秒'

    doc.add_paragraph()


# 绘制条形图
plt.figure(figsize=(12, 8))

color_map = plt.get_cmap('tab20')
color_idx = 0

for idx, indicator in enumerate(indicators):
    plt.subplot(2, 2, idx + 1)
    bars = []
    for i, (ip, values) in enumerate(ip_performance.items()):
        bar = plt.bar(i, statistics.mean(values[indicator]), color=color_map(color_idx))
        bars.append(bar[0])
        color_idx = (color_idx + 1) % 20
    plt.xlabel('服务器 IP')
    plt.ylabel('平均性能')
    plt.title(indicator)
    plt.xticks(range(len(ip_performance)), list(ip_performance.keys()), rotation=45)
    plt.legend(bars, list(ip_performance.keys()))
    
plt.tight_layout()
chart_filename = '性能比较图.png'
plt.savefig(chart_filename)
plt.close()

# 插入图表到文档中
doc.add_heading('性能指标比较', level=2)
doc.add_picture(chart_filename, width=Inches(6), height=Inches(4.5))
doc.add_paragraph()

# 性能与稳定性分析——权重
doc.add_heading('权重', level=2)
doc.add_paragraph('根据各服务器各项指标的数值大小，CPU speed(events/s)、Memory speed(MiB/s)、IO speed(次/秒)、Throughput speed(MiB/s)相对大小约为8000:8000:350:1.5')
doc.add_paragraph('这里采用加权的方式以均衡数值大小的影响,使四项指标加权后大小相等')

# 计算权重
sum_nums = 1 + 1 + 8000/350 + 8000/1.5
scale_factor = 1 / sum_nums
num1 = 1 * scale_factor
num2 = 1 * scale_factor
num3 = (8000/350) * scale_factor
num4 = (8000/1.5) * scale_factor
weights = [num1, num2, num3, num4]

doc.add_paragraph('根据数据计算，将四个指标的权重分配如下：')
for i in range(len(indicators)):
    doc.add_paragraph(f'{indicators[i]} 的权重为 {weights[i]:.10f}')

# 计算性能综合得分，越高越好
def calculate_performance_score(ip_data):
    scores = [statistics.mean(ip_data[indicator]) for indicator in indicators]
    weighted_scores = [score * weight for score, weight in zip(scores, weights)]
    return sum(weighted_scores)

# 重新计算性能综合得分
def calculate_performance_score(ip_data):
    scores = [statistics.mean(ip_data[indicator]) for indicator in indicators]
    weighted_scores = [score * weight for score, weight in zip(scores, weights)]
    return sum(weighted_scores)

# 找出性能最强的服务器
best_performance_ip = max(ip_performance.items(), key=lambda x: calculate_performance_score(x[1]))[0]

# 更新权重后的稳定性综合得分和稳定性最强的服务器
def calculate_stability_score(ip_data):
    stdevs = [statistics.stdev(ip_data[indicator]) for indicator in indicators]
    weighted_stdevs = [-stdev * weight for stdev, weight in zip(stdevs, weights)]
    return sum(weighted_stdevs)

best_stability_ip = max(ip_performance.items(), key=lambda x: calculate_stability_score(x[1]))[0]


# 思路和分析过程
doc.add_heading('思路和分析过程', level=2)
doc.add_paragraph('在评估不同服务器性能时，我们采取了以下思路和分析过程：')
doc.add_paragraph('1. 平均性能分析：我们首先关注各指标的平均性能。平均值是对服务器在不同性能指标上的典型表现的一个衡量。')
doc.add_paragraph('2. 指标稳定性分析：我们通过计算每个指标的标准差来了解数据的离散程度。标准差越小表示数据越稳定，波动越小，代表服务器性能越稳定。')
doc.add_paragraph('3. 综合分析：通过综合平均性能和指标稳定性，我们可以得出综合评估。一个服务器在某个特定指标上表现出色，但在其他指标上可能波动较大，可能导致整体性能不稳定。')
doc.add_paragraph('通过平均性能和稳定性结合考虑，我们可以找到在各项性能指标下表现较好且相对稳定的服务器。')

# 总结部分
doc.add_heading('总结', level=2)
doc.add_paragraph(f'性能最强的服务器：{best_performance_ip}')
doc.add_paragraph(f'稳定性最佳的服务器：{best_stability_ip}')

# 保存文档
report_file = '综合性能测试报告.docx'
doc.save(report_file)

print(f'报告已生成：{report_file}')
print(f'图表已生成：{chart_filename}')
